package com.twu.biblioteca;

import com.twu.biblioteca.Model.BookList;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BookReturnService implements Service {
    private BookList bookList;

    public BookReturnService(BookList bookList) {
        this.bookList = bookList;
    }

    @Override
    public String getServiceDescription() {
        return "Return Book";
    }

    @Override
    public Menu getMenu() {
        return null;
    }

    public void doService() {
        System.out.println("Enter the book ID:");
        String bookID = getBookID();
        String result = returnBook(bookID);
        System.out.println(result);
    }

    public static String getBookID() {
        BufferedReader selection = new BufferedReader(new InputStreamReader(System.in));
        try {
            return selection.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "That is not a valid book to return";
    }

    public String returnBook(String bookID) {
        String result = "Thank you for returning the book";
        if (isBookCanBeCheckOut(bookID)) {
            bookList.updateBookList(bookID, false, null);
        } else {
            result = "That is not a valid book to return";
        }
        return result;
    }

    private boolean isBookCanBeCheckOut(String bookID) {
        if (bookList.getBookList().containsKey(bookID) && bookList.getBookList().get(bookID).isCheckOut()) {
            return true;
        }
        return false;
    }
}
